package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.event.MyCarInfoChangeEvent;
import com.chexiehui.jc.mvp.mine.MyCarEditCovenant;
import com.chexiehui.jc.mvp.mine.MyCarEditPresenter;
import com.chexiehui.jc.utils.AliossUtil;
import com.chexiehui.jc.utils.GlideEngine;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.LocalMediaUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * @Description 我的爱车修改
 * @Auth SongJun
 * @Date 2020/05/21 00:18
 **/
public class MyCarEditActivity extends BaseMvpActivity<MyCarEditPresenter> implements MyCarEditCovenant.View {
    @BindView(R.id.tv_car_model_pre)
    TextView tvCarModelPre;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.rl_choose_model_container)
    RelativeLayout rlChooseModelContainer;
    @BindView(R.id.iv_travel_license)
    ImageView ivTravelLicense;
    @BindView(R.id.tv_travel_license_tip)
    TextView tvTravelLicenseTip;
    @BindView(R.id.rl_travel_license_container)
    RelativeLayout rlTravelLicenseContainer;
    @BindView(R.id.iv_driver_license)
    ImageView ivDriverLicense;
    @BindView(R.id.tv_driver_license_tip)
    TextView tvDriverLicenseTip;
    @BindView(R.id.rl_driver_license_container)
    RelativeLayout rlDriverLicenseContainer;
    @BindView(R.id.tv_resume_reason)
    TextView tvResumeReason;
    @BindView(R.id.ll_resume_reason)
    LinearLayout llResumeReason;
    @BindView(R.id.rtv_submit)
    RadiusTextView rtvSubmit;

    private CarInfo myCarInfo;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            myCarInfo = (CarInfo) bundle.getSerializable("entity");
        }
        if (myCarInfo == null) {
            myCarInfo = new CarInfo();
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("认证信息");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_car_add;
    }

    @Override
    protected void initView(Bundle var1) {
        tvCarModel.setText(myCarInfo.getSeriesName() + " " + myCarInfo.getName());
        GlideUtil.loadImageViewCrop(mContext, myCarInfo.getTravellicenseImg(), ivTravelLicense,
                R.drawable.shape_square, R.drawable.shape_square);
        GlideUtil.loadImageViewCrop(mContext, myCarInfo.getDriverslicenseImg(), ivDriverLicense,
                R.drawable.shape_square, R.drawable.shape_square);
        if (StringUtils.isTrimEmpty(myCarInfo.getTravellicenseImg())) {
            tvTravelLicenseTip.setVisibility(View.VISIBLE);
            ivTravelLicense.setImageResource(R.drawable.shape_square);
        } else {
            tvTravelLicenseTip.setVisibility(View.GONE);
        }
        if (StringUtils.isTrimEmpty(myCarInfo.getDriverslicenseImg())) {
            tvDriverLicenseTip.setVisibility(View.VISIBLE);
            ivDriverLicense.setImageResource(R.drawable.shape_square);
        } else {
            tvDriverLicenseTip.setVisibility(View.GONE);
        }
        llResumeReason.setVisibility(View.GONE);
        if(myCarInfo.getApplicationState().equals("1")){
            rtvSubmit.setText("已认证");
            rtvSubmit.setEnabled(false);
            rtvSubmit.setVisibility(View.INVISIBLE);
        }else if(myCarInfo.getApplicationState().equals("2")){
            rtvSubmit.setText("重新申请");
            rtvSubmit.setEnabled(true);
            llResumeReason.setVisibility(View.VISIBLE);
            tvResumeReason.setText(myCarInfo.getOpinion());
        }else{
            rtvSubmit.setText("申请中");
            rtvSubmit.setEnabled(false);
        }
    }

    @OnClick({R.id.rl_choose_model_container, R.id.rl_travel_license_container, R.id.rl_driver_license_container, R.id.rtv_submit})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        if(myCarInfo.getApplicationState().equals("0")){
            return;
        }
        switch (view.getId()) {
            case R.id.rl_choose_model_container:
                startActivityForResult(ChooseCarModelActivity.class, 200);
                break;
            case R.id.rl_travel_license_container:
                applyPhotoPermission(300);
                break;
            case R.id.rl_driver_license_container:
                applyPhotoPermission(400);
                break;
            case R.id.rtv_submit:
                mvpPresenter.editCar();
                break;
        }
    }

    private void applyPhotoPermission(final int code) {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
                        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
                        // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .setPictureWindowAnimationStyle(windowAnimationStyle)// 自定义相册启动退出动画
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                .enableCrop(true)// 是否裁剪
                                .cropWH(95, 66)
                                .withAspectRatio(95, 66)
                                .showCropFrame(true)
                                .freeStyleCropEnabled(false)
                                .scaleEnabled(false)
                                .showCropGrid(false)
                                .showCropFrame(true)
                                .compress(true)// 是否压缩
                                .compressQuality(90)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(false)//同步false或异步true 压缩 默认同步
                                .queryMaxFileSize(20)// 只查多少M以内的图片、视频、音频  单位M
                                .isGif(false)// 是否显示gif图片
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .recordVideoSecond(60)//录制视频秒数 默认60s
                                .forResult(code);//结果回调onActivityResult code*/
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_CARAME).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权打开相机和相册的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        CarSeriesInfo carSeriesInfo = (CarSeriesInfo) data.getSerializableExtra("seriesInfo");
                        CarInfo carInfo = (CarInfo) data.getSerializableExtra("carInfo");
                        if (carSeriesInfo != null && carInfo != null) {
                            myCarInfo.setCarTypeId(carInfo.getCarTypeId());
                            tvCarModel.setText(carSeriesInfo.getName() + " " + carInfo.getName());
                        }
                    }
                }
                break;
            case 300: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadTravelLicenseImage(path);
                }
            }
            break;
            case 400: {
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadDriverLicenseImage(path);
                }
            }
            break;
        }
    }

    @Override
    protected MyCarEditPresenter createPresenter() {
        return new MyCarEditPresenter(this);
    }

    @Override
    public void onUploadTravelLicenseImageSuccess(BaseModel<String> successResult) {
        myCarInfo.setTravellicenseImg(successResult.getData());
        tvTravelLicenseTip.setVisibility(View.GONE);
        GlideUtil.loadImageViewCrop(mContext, AliossUtil.getEndPointFileUrl(myCarInfo.getTravellicenseImg()), ivTravelLicense,
                R.drawable.shape_square, R.drawable.shape_square);
    }

    @Override
    public void onUploadTravelLicenseImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        if (StringUtils.isTrimEmpty(myCarInfo.getTravellicenseImg())) {
            tvTravelLicenseTip.setVisibility(View.VISIBLE);
            ivTravelLicense.setImageResource(R.drawable.shape_square);
        } else {
            tvTravelLicenseTip.setVisibility(View.GONE);
        }
    }

    @Override
    public void onUploadDriverLicenseImageSuccess(BaseModel<String> successResult) {
        myCarInfo.setDriverslicenseImg(successResult.getData());
        tvDriverLicenseTip.setVisibility(View.GONE);
        GlideUtil.loadImageViewCrop(mContext, AliossUtil.getEndPointFileUrl(myCarInfo.getTravellicenseImg()), ivDriverLicense,
                R.drawable.shape_square, R.drawable.shape_square);
    }

    @Override
    public void onUploadDriverLicenseImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        if (StringUtils.isTrimEmpty(myCarInfo.getDriverslicenseImg())) {
            tvDriverLicenseTip.setVisibility(View.VISIBLE);
            ivDriverLicense.setImageResource(R.drawable.shape_square);
        } else {
            tvDriverLicenseTip.setVisibility(View.GONE);
        }
    }

    @Override
    public void onEditCarSuccess(BaseModel<Object> successResult) {
        showToast("保存成功");
        EventBus.getDefault().post(new MyCarInfoChangeEvent());
        onBackPressed();
    }

    @Override
    public void onEditCarFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getCarId() {
        return myCarInfo.getId();
    }

    @Override
    public String getCarTypeId() {
        return myCarInfo.getCarTypeId();
    }

    @Override
    public String getTravelLicenseImage() {
        return myCarInfo.getTravellicenseImg();
    }

    @Override
    public String getDriverLicenseImage() {
        return myCarInfo.getDriverslicenseImg();
    }

}
